import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useUserStore } from './user'

export const useOrderStore = defineStore('order', () => {
  const userStore = useUserStore()
  const orderList = ref(JSON.parse(localStorage.getItem('order_list')) || [])

  const order_id_index = ref(localStorage.getItem('order_id_index') || 0)

  const setOrderList = obj => {
    if (obj) {
      obj.id = +order_id_index.value + 1
      obj.userId = userStore.userId
      order_id_index.value = obj.id
      orderList.value.unshift(obj)
      localStorage.setItem('order_list', JSON.stringify(orderList.value))
      localStorage.setItem('order_id_index', order_id_index.value)
    }
  }

  const delOrderList = id => {
    if (id) {
      orderList.value = orderList.value.filter(item => item.id !== id)
      localStorage.setItem('order_list', JSON.stringify(orderList.value))
    }
  }
  return {
    orderList,
    order_id_index,
    setOrderList,
    delOrderList
  }
})
